package com.berwin.bmfb.views;

import com.berwin.bmfb.entity.BMChar;
import com.berwin.bmfb.entity.BMFont;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class EditorView extends BasePanel implements MouseListener {

    private BMFont bmFont = null;
    private BMChar selBMChar = null;
    private JSpinner spScale = null;

    private Color bgColor = Color.WHITE;
    private Color borderColor = Color.RED;
    private Color txtColor = Color.BLACK;

    public EditorView(MainView mainView, BMFont bmFont) {
        super(mainView);
        this.bmFont = bmFont;

        this.setLayout(new BorderLayout());

        // center
        JPanel center = new JPanel();
        this.add(center, BorderLayout.CENTER);

        // south
        JPanel south = new JPanel(new GridLayout(1, 8 + 1));
        this.add(south, BorderLayout.SOUTH);

        JButton btnDoLayout = new JButton("重排");
        south.add(btnDoLayout);
        btnDoLayout.addActionListener(e -> this.mainView.handleDoLayoutChars());

        JLabel lblScale = new JLabel("缩放:");
        lblScale.setHorizontalAlignment(JLabel.RIGHT);
        south.add(lblScale);
        SpinnerModel model = new SpinnerNumberModel(1, -5, 5, 0.1);
        this.spScale = new JSpinner(model);
        south.add(this.spScale);
        this.spScale.addChangeListener(e -> this.repaint());

        JLabel lblBackground = new JLabel("背景:");
        lblBackground.setHorizontalAlignment(JLabel.RIGHT);
        south.add(lblBackground);
        JPanel pBackground = new JPanel();
        pBackground.setBackground(this.bgColor);
        south.add(pBackground);
        pBackground.setName("background");
        pBackground.addMouseListener(this);
        pBackground.setPreferredSize(new Dimension(30, 30));

        JLabel lblBorder = new JLabel("边框:");
        lblBorder.setHorizontalAlignment(JLabel.RIGHT);
        south.add(lblBorder);
        JPanel pBorder = new JPanel();
        pBorder.setBackground(this.borderColor);
        south.add(pBorder);
        pBorder.setName("border");
        pBorder.addMouseListener(this);

        JLabel lblText = new JLabel("文字:");
        lblText.setHorizontalAlignment(JLabel.RIGHT);
        south.add(lblText);
        JPanel pText = new JPanel();
        pText.setBackground(this.txtColor);
        south.add(pText);
        pText.setName("text");
        pText.addMouseListener(this);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        double scale = (double) this.spScale.getValue();
        // 绘制背景
        Rectangle rect = this.bmFont.getRect();
        g.setColor(this.bgColor);
        g.fillRect((int) (rect.x * scale), (int) (rect.y * scale), (int) (rect.width * scale), (int) (rect.height * scale));

        List<BMChar> bmCharList = this.bmFont.getBmChars();
        for (int i = 0; i < bmCharList.size(); i++) {
            BMChar bmChar = bmCharList.get(i);
//            bmChar.drawLetter(g, scale, this.txtColor);
            bmChar.drawImage(g, scale, this.bmFont.getPadding());
        }
        if (this.selBMChar != null) {
            this.selBMChar.drawSelected(g, scale, this.borderColor);
        }
    }

    @Override
    public void onUpdate() {
        this.repaint();
    }

    @Override
    public void onSelectLetter(int idx) {
        if (idx < 0 || idx >= this.bmFont.getBmChars().size())
            return;
        this.isFromSelected = true;
        this.giveUpListenValueChange = true;
        this.selBMChar = this.bmFont.getBmChars().get(idx);
        this.repaint();
        this.isFromSelected = false;
        this.giveUpListenValueChange = false;
        this.onValueChanged();
    }

    @Override
    public void onValueChanged() {

    }

    @Override
    public void doLayoutChars() {
        super.doLayoutChars();
        // 使用算法重新调整图片位置
        // 暂时剔除参与绘制的 空格/制表符
        List<BMChar> tmpRemoved = new ArrayList<>();
        Iterator<BMChar> it = this.bmFont.getBmChars().iterator();
        while (it.hasNext()) {
            BMChar bmChar = (BMChar) it.next();
            if (bmChar.isWithoutDraw()) {
                tmpRemoved.add(bmChar);
                it.remove();
            }
        }
        int size = this.bmFont.getBmChars().size();
        if (size <= 0)
            return;
        int padding = this.bmFont.getPadding();
        int rows = (int) Math.sqrt(size);
        int cols = (int) Math.ceil(size / (float) rows);
//        System.out.println(size + " 行:" + rows + " 列:" + cols);
        int x = padding, y = padding;
        for (int i = 0; i < cols; i++) {
            int nextMaxX = x;
            for (int j = 0; j < rows; j++) {
                int idx = (i * rows) + j;
                if (idx < 0 || idx >= this.bmFont.getBmChars().size())
                    continue;
                BMChar bmChar = this.bmFont.getBmChars().get(idx);
                bmChar.setX(x);
                bmChar.setY(y);
//                System.out.println(bmChar.getLetter() + " x:" + bmChar.getX() + " y:" + bmChar.getY());
                y += (padding + bmChar.getHeight() + 1);
                // 下一个最大x
                nextMaxX = Math.max(nextMaxX, x + bmChar.getWidth() + padding + 1);
            }
            x = nextMaxX;
            y = padding;
        }
        this.repaint();
        for (BMChar bmChar : tmpRemoved) {
            this.bmFont.getBmChars().add(bmChar);
        }
    }

    @Override
    public void onBMFontUpdated(BMFont bmFont) {
        this.giveUpListenValueChange = true;
        this.bmFont = bmFont;
        this.repaint();
        this.giveUpListenValueChange = false;
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        JPanel panel = (JPanel) e.getSource();
        String title = "";
        Color originColor = Color.GRAY;
        if (panel.getName() == "background") {
            title = "背景颜色";
            originColor = this.bgColor;
        } else if (panel.getName() == "border") {
            title = "边框颜色";
            originColor = this.borderColor;
        } else if (panel.getName() == "text") {
            title = "文本颜色";
            originColor = this.txtColor;
        }
        Color color = JColorChooser.showDialog(this.mainView, "选取" + title, originColor);
        if (color == null)
            return;

        panel.setBackground(color);
        if (panel.getName() == "background") {
            this.bgColor = color;
        } else if (panel.getName() == "border") {
            this.borderColor = color;
        } else if (panel.getName() == "text") {
            this.txtColor = color;
        }
        this.repaint();
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}
